package com.ruoyi.project.payment.order.service.impl;

import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IpUtils;
import com.ruoyi.common.utils.JsonUtil;
import com.ruoyi.common.utils.MoneyUtil;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.framework.aspectj.lang.annotation.DataSource;
import com.ruoyi.framework.aspectj.lang.enums.DataSourceType;
import com.ruoyi.project.payment.order.domain.Order;
import com.ruoyi.project.payment.order.mapper.OrderMapper;
import com.ruoyi.project.payment.order.service.IOrderService;
import net.ipip.ipdb.CityInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 支付订单Service业务层处理
 *
 * @author shixiangwen
 * @date 2019-12-04
 */
@Service
@DataSource(value = DataSourceType.PAYMENT)
public class OrderServiceImpl implements IOrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 查询支付订单
     *
     * @param id 支付订单ID
     * @return 支付订单
     */
    @Override
    public Order selectOrderById(Long id) {
        return orderMapper.selectOrderById(id);
    }

    /**
     * 查询支付订单列表
     *
     * @param order 支付订单
     * @return 支付订单
     */
    @Override
    public List<Order> selectOrderList(Order order) {
        List<Order> orders = orderMapper.selectOrderList(order);
        if (!CollectionUtils.isEmpty(orders)) {
            orders.forEach(item -> {
                item.setYuan(MoneyUtil.fee2yuan(item.getTotalFee()).toString());
                CityInfo cityInfo = IpUtils.getCityInfo(item.getIp());
                if (cityInfo != null) {
                    item.setIpInfo(cityInfo.getRegionName() + " " + cityInfo.getCityName());
                }
            });
        }
        return orders;
    }

    /**
     * 新增支付订单
     *
     * @param order 支付订单
     * @return 结果
     */
    @Override
    public int insertOrder(Order order) {
        return orderMapper.insertOrder(order);
    }

    /**
     * 修改支付订单
     *
     * @param order 支付订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order) {
        return orderMapper.updateOrder(order);
    }

    /**
     * 删除支付订单对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteOrderByIds(String ids) {
        return orderMapper.deleteOrderByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除支付订单信息
     *
     * @param id 支付订单ID
     * @return 结果
     */
    @Override
    public int deleteOrderById(Long id) {
        return orderMapper.deleteOrderById(id);
    }

    @Override
    public boolean reNotify(Long id) {
        Order order = orderMapper.selectOrderById(id);
        if (order == null) {
            throw new BusinessException("订单不存在[" + id + "]");
        }
        if (order.getPayResult() != 1) {
            throw new BusinessException("订单未支付[" + id + "]");
        }

        if (order.getNotifyStatus() == 1) {
            throw new BusinessException("订单已经通知成功[" + id + "]");
        }

        try {
            String s = HttpUtils.sendPost(order.getNotifyUrl(), "orderNo=" + order.getBizOrderNo() + "&result=" + order.getPayResult());
            log.debug("订单通知返回.notifyUrl[{}], response[{}]", order.getNotifyUrl(), s);
            Map<String, Object> res = JsonUtil.toMap(s);
            if (Integer.parseInt(res.get("status").toString()) == 200) {
                order.setNotifyStatus(1L);
                order.setNotifyTime(DateUtils.getNowDate());
                orderMapper.updateOrder(order);
                return true;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return false;
    }

    @Override
    public boolean refundNotify(Long id, String refundRemark) {

        Order order = orderMapper.selectOrderById(id);
        if (order == null) {
            throw new BusinessException("订单不存在[" + id + "]");
        }
        if (order.getPayResult() != 1) {
            throw new BusinessException("订单未支付[" + id + "]");
        }

        if (order.getStatus() != 1) {
            throw new BusinessException("不是在完成状态[" + id + "]");
        }

        try {
            String s = HttpUtils.sendPost(order.getRefundNotifyUrl(), "orderNo=" + order.getBizOrderNo() + "&result=1");
            log.debug("订单退款通知返回.notifyUrl[{}], response[{}]", order.getRefundNotifyUrl(), s);
            Map<String, Object> res = JsonUtil.toMap(s);
            if (Integer.parseInt(res.get("status").toString()) == 200) {
                order.setStatus(3L);
                order.setRefundRemark(refundRemark);
                orderMapper.updateOrder(order);
                return true;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return false;
    }

    @Override
    public int getOrderCount(String app, String date, int status) {
        return orderMapper.getOrderCount(app, date, status);
    }


    @Override
    public int getOrderAmount(String app, String paytype, String date, int status) {
        return getOrderAmount(app, paytype, "", date, status);
    }

    @Override
    public int getOrderAmount(String app, String paytype, String excludePaytype, String date, int status) {
        Integer amount = orderMapper.getOrderAmount(app, paytype, excludePaytype, date, status);
        return amount == null ? 0 : amount;
    }

    public int getOrderMonthAmount(String app, String paytype, String month, int status) {
        return getOrderMonthAmount(app, paytype, "", month, status);
    }

    @Override
    public int getOrderMonthAmount(String app, String paytype, String excludePaytype, String month, int status) {
        String startDate = month + "-01 00:00:00";
        String endDate = month + "-31 23:59:59";
        Integer amount = orderMapper.getOrderMonthAmount(app, paytype, excludePaytype, startDate, endDate, status);
        return amount == null ? 0 : amount;
    }

    @Override
    public List<Order> getOrderList(String date, int status) {
        return orderMapper.getOrderList(date, status);
    }

    @Override
    public List<Order> getOrderListMonth(String month, int status) {
        String startDate = month + "-01 00:00:00";
        String endDate = month + "-31 23:59:59";
        return orderMapper.getOrderListMonth(startDate, endDate, status);
    }
}
